<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { resetPassword, validateToken } from '../../api/auth'
import type { ResetPasswordRequest } from '../../types/auth'

const route = useRoute()
const router = useRouter()

// 表单数据
const resetForm = reactive<ResetPasswordRequest>({
  email: '',
  code: '',
  password: ''
})

// 确认密码字段（不计入提交数据）
const confirmPassword = ref('')

// 令牌相关
const isTokenValid = ref(true)
const isValidating = ref(true)

// 表单验证规则
const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email' as const, message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 30, message: '密码长度应为6-30个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== resetForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 表单引用
const formRef = ref()

// 提交状态
const isSubmitting = ref(false)
const isSubmitted = ref(false)

// 验证令牌
const checkToken = async () => {
  const token = route.query.token as string
  
  if (!token) {
    isTokenValid.value = false
    isValidating.value = false
    return
  }
  
  try {
    resetForm.code = token
    const response = await validateToken(token)
    
    if (response.data && response.data.valid) {
      isTokenValid.value = true
    } else {
      isTokenValid.value = false
    }
  } catch (error) {
    console.error('Token validation error:', error)
    isTokenValid.value = false
  } finally {
    isValidating.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    isSubmitting.value = true
    
    try {
      const token = route.query.token as string
      if (!token) {
        ElMessage.error('重置链接无效')
        return
      }
      
      // 使用新的API函数
      const response = await resetPassword(token, resetForm.password)
      
      if (response.success) {
        isSubmitted.value = true
        ElMessage.success('密码重置成功，请使用新密码登录')
      } else {
        ElMessage.error(response.message || '重置失败，请稍后再试')
      }
    } catch (error: any) {
      console.error('密码重置失败:', error)
      
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.message || '重置失败，请稍后再试')
      } else {
        ElMessage.error('重置失败，请稍后再试')
      }
    }
  } catch (error: any) {
    console.error('表单验证失败:', error)
  } finally {
    isSubmitting.value = false
  }
}

// 返回登录页面
const goToLogin = () => {
  router.push({ name: 'Login' })
}

// 初始化
onMounted(() => {
  checkToken()
  
  // 如果URL中包含email参数，自动填入
  const email = route.query.email as string
  if (email) {
    resetForm.email = email
  }
})
</script>

<template>
  <div class="reset-password-container">
    <div class="reset-password-form-wrapper">
      <div class="reset-password-header">
        <h1 class="text-2xl font-bold mb-6">重置密码</h1>
      </div>
      
      <!-- 加载中 -->
      <div v-if="isValidating" class="flex justify-center py-8">
        <el-spinner></el-spinner>
      </div>
      
      <!-- 令牌无效 -->
      <div v-else-if="!isTokenValid" class="token-invalid">
        <el-icon class="error-icon" color="#F56C6C"><circle-close /></el-icon>
        <p class="text-center mb-4">
          重置链接无效或已过期！
        </p>
        <p class="text-center text-gray-600 text-sm mb-6">
          请重新申请重置密码，或联系管理员获取帮助。
        </p>
        
        <el-button type="primary" class="w-full" @click="goToLogin">
          返回登录
        </el-button>
      </div>
      
      <!-- 重置成功 -->
      <div v-else-if="isSubmitted" class="success-message">
        <el-icon class="success-icon" color="#67C23A"><check-circle /></el-icon>
        <p class="text-center mb-4">
          密码重置成功！
        </p>
        <p class="text-center text-gray-600 text-sm mb-6">
          您现在可以使用新密码登录账户。
        </p>
        
        <el-button type="primary" class="w-full" @click="goToLogin">
          前往登录
        </el-button>
      </div>
      
      <!-- 重置表单 -->
      <div v-else>
        <p class="text-gray-600 text-center mb-6">
          请输入您的新密码
        </p>
        
        <el-form
          ref="formRef"
          :model="resetForm"
          :rules="rules"
          label-position="top"
          class="reset-password-form"
        >
          <el-form-item label="电子邮箱" prop="email">
            <el-input
              v-model="resetForm.email"
              placeholder="请输入您的邮箱"
              prefix-icon="message"
            />
          </el-form-item>
          
          <el-form-item label="新密码" prop="password">
            <el-input
              v-model="resetForm.password"
              type="password"
              placeholder="请输入新密码"
              prefix-icon="lock"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              prefix-icon="lock"
              show-password
            />
          </el-form-item>
          
          <el-button
            type="primary"
            class="w-full"
            :loading="isSubmitting"
            @click="handleSubmit"
          >
            重置密码
          </el-button>
          
          <div class="text-center mt-4">
            <el-button type="text" @click="goToLogin">返回登录</el-button>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<style scoped>
.reset-password-container {
  min-height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 2rem;
}

.reset-password-form-wrapper {
  width: 100%;
  max-width: 400px;
  padding: 2rem;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.reset-password-header {
  text-align: center;
  margin-bottom: 1.5rem;
}

.reset-password-form {
  width: 100%;
}

.success-message,
.token-invalid {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.success-icon,
.error-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}
</style> 